package com.lysj.bhp.wallet.service;

import com.lysj.bhp.wallet.base.WalletContent;
import com.lysj.bhp.wallet.domain.BitCoinAddress;
import com.lysj.bhp.wallet.domain.BitCoinWallet;
import com.lysj.bhp.wallet.util.BlockChainUtil;
import com.lysj.bhp.util.random.FormatUtil;
import com.lysj.bhp.util.web.ParamUtil;
import com.lysj.bhp.util.web.Resp;
import info.blockchain.api.wallet.entity.Address;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class BlockChainService extends WalletContent {
    private Logger logger = LoggerFactory.getLogger(BlockChainService.class);

    /*
        创建一个比特币钱包，并包含一个子地址
     */
    public Resp createBitcoinWallet(String email) {
        //创建一个新的比特币钱包
        if (ParamUtil.isBlack(email)) {
            email = currentUser().getEmail();
        }
        String password = ParamUtil.uuid();
        Map<String, String> resultMap = BlockChainUtil.createWallet(password, email);
        if (resultMap == null || resultMap.size() == 0) {
            return new Resp(Resp.INNER_ERROR, "创建钱包失败,请重试!");
        }
        String guid = resultMap.get("guid");
        if (ParamUtil.isBlack(guid)) {
            return new Resp(Resp.INNER_ERROR, "创建钱包失败,请重试!");
        }
        BitCoinWallet bitCoinWallet = new BitCoinWallet();
        bitCoinWallet.setUserId(currentUser().getUserId());
        bitCoinWallet.setEmail(email);
        bitCoinWallet.setPassword(password);
        bitCoinWallet.setGuid(guid);
        bitCoinWallet.setHdAddress(resultMap.get("address"));
        bitCoinWallet.setLabel(resultMap.get("label"));
        bitCoinWallet.setBalance(BigDecimal.ZERO);
        bitCoinWallet.setFreezeBalance(BigDecimal.ZERO);
        bitCoinWallet.setAvailBalance(BigDecimal.ZERO);
        bitCoinWallet.setBookKeepBalance(BigDecimal.ZERO);
        bitcoinWalletRepository.save(bitCoinWallet);
        logger.info("创建了一个比特币钱包--bitcoinWalletId:" + bitCoinWallet.getBitcoinWalletId());
        //创建一个新的比特币地址
        String lable = null;
        try {
            lable = FormatUtil.dateToString(new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
        Address address = BlockChainUtil.createAddress(bitCoinWallet.getGuid(), bitCoinWallet.getPassword(), lable);
        if (address == null) {
            return new Resp(Resp.INNER_ERROR, "创建地址失败,请重试!");
        }

        BitCoinAddress bitCoinAddress = new BitCoinAddress();
        bitCoinAddress.setUserId(currentUser().getUserId());
        bitCoinAddress.setBitcoinWalletId(bitCoinWallet.getBitcoinWalletId());

        bitCoinAddress.setAddress(address.getAddress());
        bitCoinAddress.setLabel(lable);
        bitCoinAddress.setBalance(0);
        bitCoinAddress.setTotalReceived(0);

        logger.info("创建了一个比特币地址--address:" + address.getAddress());
        bitcoinAddressRepository.save(bitCoinAddress);

        bitCoinWallet.setLastAddress(bitCoinAddress.getAddress());
        bitcoinWalletRepository.save(bitCoinWallet);

        Map<String, String> respMap = new HashMap<>();
//        respMap.put("hdAddress", bitCoinWallet.getHdAddress()); // hd地址
//        respMap.put("lastAddress", bitCoinWallet.getLastAddress()); // 最新的一个子地址
        return new Resp(Resp.SUCCESS, "创建比特币钱包成功",bitCoinWallet.getLastAddress());
    }

    /**
     * 获取一个新的比特币地址
     * @param lable
     * @return
     */
    public Resp refreshBitcoinAddress(String lable) {
        BitCoinWallet bitCoinWallet = bitcoinWalletRepository.findByUserId(currentUser().getUserId());
        if (bitCoinWallet == null) {
            return new Resp(Resp.PARAM_ERROR, "您还没有比特币钱包,请先创建一个");
        }
        if (ParamUtil.isBlack(lable)) {
            try {
                lable = FormatUtil.dateToString(new Date());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Address address = BlockChainUtil.createAddress(bitCoinWallet.getGuid(), bitCoinWallet.getPassword(), lable);
        if (address == null) {
            return new Resp(Resp.INNER_ERROR, "创建地址失败,请重试!");
        }

        BitCoinAddress bitCoinAddress = new BitCoinAddress();
        bitCoinAddress.setUserId(currentUser().getUserId());
        bitCoinAddress.setBitcoinWalletId(bitCoinWallet.getBitcoinWalletId());

        bitCoinAddress.setAddress(address.getAddress());
        bitCoinAddress.setLabel(lable);
        bitCoinAddress.setBalance(0);
        bitCoinAddress.setTotalReceived(0);

        logger.info("创建了一个比特币地址--address:" + address.getAddress());
        bitcoinAddressRepository.save(bitCoinAddress);
        // 将新的地址保存到数据库
        bitCoinWallet.setLastAddress(bitCoinAddress.getAddress());
        bitcoinWalletRepository.save(bitCoinWallet);
        return new Resp(Resp.SUCCESS, "创建以太币地址成功", address);
    }

}
